package com.jwmp.rbac.web.servlet;

import com.jwmp.core.servlet.BaseServlet;
import com.jwmp.core.util.PageResult;
import com.jwmp.core.util.QueryObject;
import com.jwmp.core.util.QueryObjectUtil;
import com.jwmp.rbac.domain.Role;
import com.jwmp.rbac.service.IRoleService;
import com.jwmp.rbac.service.impl.RoleServiceImpl;
import com.jwmp.rbac.util.SetPermission;
import com.jwmp.core.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet("/role/*")
public class RoleServlet extends BaseServlet {
    private IRoleService roleService = new RoleServiceImpl();

    @SetPermission(moduleName = "角色管理",name="角色列表",expression = "/role/list")
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        QueryObject qo = QueryObjectUtil.req2qo(req);

        PageResult pageResult = roleService.queryList(qo);
        req.setAttribute("pageResult",pageResult);
        req.getRequestDispatcher("/WEB-INF/views/rbac/role_list.jsp").forward(req,resp);
    }

    // 跳转到编辑页面
    @SetPermission(moduleName = "角色管理",name="角色编辑",expression = "/role/edit")
    public void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String strId = req.getParameter("id");
        if (StringUtil.hasLength(strId)) {
            Role role = roleService.selectOne(Long.valueOf(strId));
            req.setAttribute("role",role);
        }
        req.getRequestDispatcher("/WEB-INF/views/rbac/role_input.jsp").forward(req,resp);
    }

    // 角色基本信息保存或修改
    @SetPermission(moduleName = "角色管理",name="角色修改或者保存",expression = "/role/saveOrUpdate")
    public void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        Role role = new Role();
        req2role(req,role);
        if (role.getId() != null) {
            roleService.update(role);
        }else{
            roleService.insert(role);
        }
        list(req,resp);
    }

    private void req2role(HttpServletRequest req,Role role){
        String strId = req.getParameter("id");
        if (StringUtil.hasLength(strId)) {
            role.setId(Long.valueOf(strId));
        }

        String name = req.getParameter("name");
        role.setName(name);

        String introduce = req.getParameter("introduce");
        role.setIntroduce(introduce);
    }

    // 删除操作
    @SetPermission(moduleName = "角色管理",name="角色删除",expression = "/role/delete")
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String strId = req.getParameter("id");
        if (StringUtil.hasLength(strId)) {
            roleService.delete(Long.valueOf(strId));
        }
    }

}
